/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.ubhave.sensormanager.ability;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.ESSensorManager;
import com.ubhave.sensormanager.ResourceTable;
import com.ubhave.sensormanager.SensorDataListener;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.env.HumidityData;
import com.ubhave.sensormanager.data.env.LightData;
import com.ubhave.sensormanager.sensors.SensorUtils;
import com.ubhave.sensormanager.utils.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

public class LightAbility extends Ability implements Component.ClickedListener, SensorDataListener {
    private Button startBtn;
    private Button stopBtn;
    private Text temperatureData;
    private ESSensorManager sensorManager;
    private int subscriptionId;
    private SensorData mSensorData;
    private int status=0;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_light);
        startBtn = (Button) findComponentById(ResourceTable.Id_start_btn);
        stopBtn = (Button) findComponentById(ResourceTable.Id_stop_btn);
        temperatureData = (Text) findComponentById(ResourceTable.Id_data_temperature);
        startBtn.setClickedListener(this);
        stopBtn.setClickedListener(this);

    }
    @Override
    public void onClick(Component component) {
        int id = component.getId();
        switch (id){
            case ResourceTable.Id_start_btn:
                startSensor();
                break;
            case ResourceTable.Id_stop_btn:
                if (sensorManager != null) {
                    try {
                        sensorManager.unsubscribeFromSensorData(subscriptionId);
                        status=0;
                        LogUtil.loge("onClick"+status);
                    } catch (ESException e) {
                        e.printStackTrace();
                    }
                }
                break;

        }
    }
    private void startSensor(){
        try {
            sensorManager = ESSensorManager.getSensorManager(getContext());
            LogUtil.loge("===走了走了第一步:");
            subscriptionId = sensorManager.subscribeToSensorData(SensorUtils.SENSOR_TYPE_LIGHT, this);
            LogUtil.loge("===走了走了第二步:"+subscriptionId);
            status=1;
            LogUtil.loge("startSensor"+status);
        } catch (ESException e) {
            ToastDialog toastDialog = new ToastDialog(getContext());
            toastDialog.setText("你的手机不支持光传感器");
            toastDialog.setAlignment(LayoutAlignment.CENTER);
            toastDialog.show();
            e.printStackTrace();
        }
    }

    @Override
    public void onDataSensed(SensorData data) {
//        LogUtil.loge("是否有回调了??");
        mSensorData = data;
        parseData(mSensorData);

    }

    private void parseData(SensorData data) {
        if(data instanceof LightData){
            LightData lightData = (LightData) data;
            long timestamp = lightData.getTimestamp();
            int sensorType = lightData.getSensorType();
            String sensorName = "";
            try {
                sensorName  = SensorUtils.getSensorName(sensorType);
            } catch (ESException e) {
                e.printStackTrace();
            }
            Date date = new Date();
            date.setTime(timestamp);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dateString = dateFormat.format(date);

            float value = lightData.getValue();
            float maxRange = lightData.getMaxRange();
            StringBuffer buffer = new StringBuffer();
            buffer.append("senseStartTime: ").append(dateString).append("\n");
            buffer.append("senseStartTimeMillis: ").append(timestamp).append("\n");
            buffer.append("dataType: ").append(sensorName).append("\n");
            buffer.append("光照强度: ").append(value).append("\n");
            buffer.append("最大等级: ").append(maxRange).append("\n");
            LogUtil.loge("获取到的光照强度为:"+value+"lx"+"    最大等级:"+maxRange);
            getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    temperatureData.setText(buffer.toString());
                }
            });
        }
    }

    @Override
    public void onCrossingLowBatteryThreshold(boolean isBelowThreshold) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {
            try {
                sensorManager.unsubscribeFromSensorData(subscriptionId);
                LogUtil.loge("onStop"+status);
            } catch (ESException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        Optional<Sequenceable> sensorDataOptional = inState.getSequenceable("sensorData");
        int status = inState.getIntValue("status");
        if(sensorDataOptional.isPresent()) {
            mSensorData = (SensorData) sensorDataOptional.get();
            parseData(mSensorData);
            LogUtil.loge("onRestoreAbilityState"+status);
            if (status==1){
                startSensor();
            }
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        if(mSensorData != null) {
            LogUtil.loge("onSaveAbilityState"+status);
            outState.putSequenceableObject("sensorData", mSensorData);
            outState.putIntValue("status",status);
        }
    }
}
